var express = require('express');
var router = express.Router();
var { user, home, area, home, } = require('../model/model');
let multiparty = require('multiparty');
let path = require('path');

// const WebSocket = require('ws');
const { WebSocketServer, WebSocket } = require('ws');
/* GET home page. */
// 用于存储用户 ID 和 WebSocket 连接的映射
const clients = new Map();
// 实时聊天 WebSocket 服务器
const wss = new WebSocketServer({ port: 3001 });  // WebSocket 服务运行在 3001 端口
wss.on('connection', (ws) => {
    // 注册连接的用户
    ws.on('message', (message) => {
        const data = JSON.parse(message);

        if (data.type === 'register') {
            // 存储用户 ID 和对应的 WebSocket 连接
            clients.set(data.userId, ws);
            console.log(`User ${data.userId} registered`);
        } else if (data.type === 'chat') {
            // 处理聊天消息
            const targetClient = clients.get(data.toUserId);

            if (targetClient && targetClient.readyState === WebSocket.OPEN) {
                // 将消息发送给接收者
                targetClient.send(JSON.stringify(data));
                console.log(`Message sent from ${data.fromUserId} to ${data.toUserId}`);
            } else {
                console.log(`User ${data.toUserId} is not connected`);
            }
        }
    });

    // 移除断开连接的用户
    ws.on('close', () => {
        for (const [userId, client] of clients.entries()) {
            if (client === ws) {
                clients.delete(userId);
                console.log(`User ${userId} disconnected`);
                break;
            }
        }
    });

    ws.on('error', (error) => {
        console.error("WebSocket error:", error);
    });
});

console.log("WebSocket server started on port 3001");

console.log('WebSocket server started on port 3001');
console.log('start success');
// 添加用户
router.post('/addUser', (req, res) => {
    user.create(req.body)
    res.send({ code: 200, msg: '添加成功' })
})
// 获取我要聊天用户
router.get('/chatUser', async (req, res) => {
    let id = req.query.id;
    let data = await user.find({ _id: id }).select('admin landlord');;
    res.send({
        code: 200,
        msg: '查询成功',
        data: data
    })
})
//点击聊天页面
router.get("/getUser", async (req, res) => {
    let id = req.query.id
    let data = await user.find({ _id: { $ne: id } });
    res.send({
        code: 200,
        msg: '查询成功',
        data: data
    })
})

// 模拟登录
router.get('/login', async (req, res) => {
    let admin = req.query.admin;
    let password = req.query.pwd;
    let data = await user.find({ admin: admin, password: password });
    res.send({
        code: 200,
        msg: '查询成功',
        data: data
    })
})
// 根据房东_id获取相关的所有房源
router.get('/getUserInfo', async (req, res) => {
    let id = req.query.id;
    console.log(id);

    try {
        // 查找与房东ID关联的房源
        const homes = await home.find({ u_id: id }).populate('u_id', 'admin landlord').populate('c_id', 'name');
        // 检查是否找到任何房源
        if (homes.length === 0) {
            return res.send({ code: 404, msg: '没有找到相关房源' });
        }
        console.log(homes);

        res.send({ code: 200, msg: '查询成功', data: homes });
    } catch (error) {
        console.log(error);
        res.send({ code: 500, msg: '服务器错误' });
    }

})

// 是否收藏
router.get('/isCollect', async (req, res) => {
    let id = req.query.id;
    try {
        // 查找房源的id进行状态修改
        let isCollect = await home.findOne({ _id: id });
        if (isCollect.collect) {
            await home.updateOne({ _id: id }, { $set: { collect: false } });
            res.send({ code: 200, msg: '取消收藏' });
        } else {
            await home.updateOne({ _id: id }, { $set: { collect: true } });
            res.send({ code: 200, msg: '收藏成功' });
        }
    } catch (error) {
        console.log(error);
        res.send({ code: 500, msg: '服务器错误' });

    }
})

//获取所有的房屋信息
router.get('/getHome', async (req, res) => {
    try {
        let data = await home.find().populate('u_id', 'admin landlord').populate('c_id', 'name');
        res.send({ code: 200, msg: '查询成功', data: data });
    } catch (error) {
        console.log(error);
        res.send({ code: 500, msg: '服务器错误' });
    }
})


// 图片上传
router.post('/upload', (req, res) => {
    let form = new multiparty.Form();
    form.uploadDir = './img';  // 上传目录
    form.parse(req, (err, fields, imgurl) => {
        if (err) {
            console.log(err);
            res.send({ code: 500, msg: '服务器错误' });
        } else {
            // 返回正确的图片路径
            const imgPath = 'http://localhost:3000/' + path.basename(imgurl.file[0].path);
            res.send({
                code: 200,
                msg: '上传成功',
                path: imgPath
            });
        }
    });
});
// 发布房屋
router.post("/addHome", (req, res) => {
    // 假设req.body.img是上传图片的路径
    const imgPath = req.body.img; // 这里应该是图片的路径，如 "http://localhost:3000/..."，确保数据类型正确

    // 创建房屋信息
    home.create({
        name: req.body.name,
        img: imgPath, // 确保这里是有效的图片路径
        price: req.body.price,
        address: req.body.address,
        home_km: "132平米",
        collect: false,
        history: false,
        u_id: req.body.u_id,
        time: new Date(),
        check: new Date(),
        leave: new Date(),
        visitorNum: "4",
        roomNum: "5",
        badNum: "3",
        cate: req.body.houseType,
        toiletNum: "2",
        book: false,
        papay: false,
        houselabel: ["3分", '停车场', '免费WIFI', '订车服务'],
        c_id: "6728a74b0c941f9090b3b72c"
    })
        .then(() => {
            res.send({ code: 200, msg: '发布成功' });
        })
        .catch((err) => {
            console.error(err);
            res.send({ code: 500, msg: '服务器错误' });
        });
});

// 添加地区
router.post('/addArea', (req, res) => {
    area.create(req.body)
    res.send({ code: 200, msg: '添加成功' })
})


//查询所有收藏的房源
router.get('/getCollect', async (req, res) => {
    try {
        let data = await home.find({ collect: true }).populate('c_id', 'name')
        res.send({ code: 200, msg: '查询成功', data: data });
    } catch (error) {
        console.log(error);
        res.send({ code: 500, msg: '服务器错误' });

    }
})

// 进行房屋日期查询
router.get('/getHomeDate', async (req, res) => {
    let data = req.query.data;
    let startDate = new Date(data);
    console.log(startDate);
    let endDate = new Date(data);
    console.log(endDate);
    // 设置 endDate 到一天的最后一刻
    endDate.setDate(endDate.getDate() + 1);
    try {
        let data1 = await home.find({
            time: {
                $gte: startDate,
                $lt: endDate
            }
        })
        res.send({ code: 200, msg: '查询成功', data: data1 });

    } catch (error) {
        console.log(error);
        res.send({ code: 500, msg: '服务器错误' });
    }
})





module.exports = router;